package es.udc.emarketapp.emarket.model.orderDetails.dao;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;

import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.sql.GeneralOperations;
import es.udc.emarketapp.emarket.model.orderDetails.vo.OrderDetailsVO;
import java.sql.Timestamp;

// An implementation of <code>SQLOrderDAO</code> for databases providing
// counter columns with JDBC 3 drivers.

public class MySQLOrderDetailsDAO extends AbstractSQLOrderDetailsDAO {

	public OrderDetailsVO create(Connection connection, OrderDetailsVO orderVO)
			throws InternalErrorException {

		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;

		try {

			// Create "preparedStatement".
			String queryString = "INSERT INTO pedido"
					+ "(n_compra, id_vendedor, valor, peso, gastos_envio, "
					+ "fecha_pago, fecha_envio) VALUES (?, ?, ?, ?, ?, ?, ?)";

			preparedStatement = connection.prepareStatement(queryString,
					Statement.RETURN_GENERATED_KEYS);

			// Fill "preparedStatement".
			int i = 1;
			preparedStatement.setLong(i++, orderVO.getnCompra());
			preparedStatement.setString(i++, orderVO.getIdVendedor());
			preparedStatement.setDouble(i++, orderVO.getValor());
			preparedStatement.setDouble(i++, orderVO.getPeso());
			preparedStatement.setDouble(i++, orderVO.getGastosEnvio());
			if (orderVO.getFechaPago() != null) {
				preparedStatement.setTimestamp(i++, new Timestamp(orderVO
						.getFechaPago().getTime().getTime()));
			} else {
				preparedStatement.setTimestamp(i++, null);
			}
			if (orderVO.getFechaEnvio() != null) {
				preparedStatement.setTimestamp(i++, new Timestamp(orderVO
						.getFechaEnvio().getTime().getTime()));
			} else {
				preparedStatement.setTimestamp(i++, null);

			}

			// Execute query.
			int insertedRows = preparedStatement.executeUpdate();

			if (insertedRows == 0) {
				throw new SQLException("No se pudo insertar la fila a la tabla"
						+ " 'Pedido'");
			}

			if (insertedRows > 1) {
				throw new SQLException("Fila duplicada en la tabla 'Pedido'");
			}

			// Get account identifier.
			resultSet = preparedStatement.getGeneratedKeys();

			if (!resultSet.next()) {
				throw new InternalErrorException(
						new SQLException(
								"el driver JDBC no ha devuelto el identificador generado"));
			}

			Long nPedido = new Long(resultSet.getLong(1));

			// Return the value object.
			return new OrderDetailsVO(nPedido.longValue(), orderVO.getnCompra(),
					orderVO.getIdVendedor(), orderVO.getValor(),
					orderVO.getPeso(), orderVO.getGastosEnvio(),
					orderVO.getFechaPago(), orderVO.getFechaEnvio());

		} catch (SQLException e) {
			throw new InternalErrorException(e);
		} finally {
			GeneralOperations.closeStatement(preparedStatement);
		}

	}

}